package com.yyy.dm.consumer.service;

import com.yyy.dm.CommonResponse;
import com.yyy.dm.VoUtil;
import com.yyy.dm.consumer.feign.base.DMImageFeign;
import com.yyy.dm.dao.CinemaMapper;
import com.yyy.dm.dao.ItemMapper;
import com.yyy.dm.item.*;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ItemConsumerService {

    @Resource
    private ItemMapper itemMapper;
    @Resource
    private CinemaMapper cinemaMapper;
    @Resource
    private DMImageFeign dmImageFeign;
    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    public CommonResponse carousel() {
        List<IndexNavHotItemsDTO> indexNavHotItemsDTOList = itemMapper.findHotItem();
        for (IndexNavHotItemsDTO indexNavHotItemsDTO : indexNavHotItemsDTOList) {
            indexNavHotItemsDTO.setImgUrl(dmImageFeign.findItemBannerByItemId(indexNavHotItemsDTO.getId()));
        }
        return VoUtil.returnSuccess(indexNavHotItemsDTOList);
    }

    public CommonResponse getItems(Long id) {
        DmItem dmItem = itemMapper.selectById(id);
        ItemDetailDTO detailDTO = new ItemDetailDTO();
        BeanUtils.copyProperties(dmItem, detailDTO);
        DMCinema dmCinema = cinemaMapper.selectById(detailDTO.getCinemaId());
        BeanUtils.copyProperties(dmCinema, detailDTO);
        detailDTO.setId(dmItem.getId());
        detailDTO.setImgUrl(dmImageFeign.findItemPosterImageByItemId(id));
        return VoUtil.returnSuccess(detailDTO);
    }

    public CommonResponse recommend() {
        List<IndexNavHotItemsDTO> indexNavHotItemsDTOList = itemMapper.findTodayHotItem();
        for (IndexNavHotItemsDTO indexNavHotItemsDTO : indexNavHotItemsDTOList) {
            indexNavHotItemsDTO.setImgUrl(dmImageFeign.findItemPosterImageByItemId(indexNavHotItemsDTO.getId()));
        }
        return VoUtil.returnSuccess(indexNavHotItemsDTOList);
    }

    public CommonResponse sell() {
        List<IndexNavHotItemsDTO> indexNavHotItemsDTOList = itemMapper.findToSaleItem();
        for (IndexNavHotItemsDTO indexNavHotItemsDTO : indexNavHotItemsDTOList) {
            indexNavHotItemsDTO.setImgUrl(dmImageFeign.findItemPosterImageByItemId(indexNavHotItemsDTO.getId()));
        }
        return VoUtil.returnSuccess(indexNavHotItemsDTOList);
    }

    public CommonResponse seniority(Long itemTypeId) {
        return VoUtil.returnSuccess(itemMapper.findRankingByItemType(itemTypeId));
    }

    public CommonResponse queryGoodsInfos(Map<String, String> param) {
        Integer areaId = Integer.parseInt(param.get("areaId"));
        String startTime = param.get("startTime");
        String endTime = param.get("endTime");
        Integer itemTypeId1 = Integer.parseInt(param.get("itemTypeId1"));
        Integer itemTypeId2 = Integer.parseInt(param.get("itemTypeId2"));
        String keyword = param.get("keyword");
        String sort = param.get("sort");
        Integer currentPage = Integer.parseInt(param.get("currentPage"));
        Integer pageSize = Integer.parseInt(param.get("pageSize"));
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        List<QueryBuilder> must = boolQueryBuilder.must();
        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
        if (areaId != 0) {
            TermQueryBuilder areaQuery = QueryBuilders.termQuery("areaid", areaId);
            must.add(areaQuery);
        }
        if (keyword != null && !"".equals(keyword)) {
            MultiMatchQueryBuilder keywordQuery = QueryBuilders.multiMatchQuery(keyword, "abstractmessage", "reminderdescription", "projectdescription", "basicdescription", "itemname").analyzer("ik_smart");
            must.add(keywordQuery);
        }
        if (startTime != null && !"".equals(startTime) && endTime != null && !"".equals(endTime)) {
            RangeQueryBuilder startTimeQuery = QueryBuilders.rangeQuery("starttime").gte(startTime).lte(endTime);
            must.add(startTimeQuery);
        }
        if (itemTypeId1 != 0) {
            TermQueryBuilder type1Query = QueryBuilders.termQuery("itemtype1id", itemTypeId1);
            must.add(type1Query);
        }
        if (itemTypeId2 != 0) {
            TermQueryBuilder type2Query = QueryBuilders.termQuery("itemtype2id", itemTypeId2);
            must.add(type2Query);
        }
        if (sort != null && !"".equals(sort)) {
            nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("starttime").order(SortOrder.DESC));
        }
        NativeSearchQuery nativeSearchQuery = nativeSearchQueryBuilder
                .withHighlightFields(new HighlightBuilder.Field("itemname"), new HighlightBuilder.Field("areaname"))
                .withHighlightBuilder(new HighlightBuilder().preTags("<span style='color:red;'>").postTags("</span>"))
                .withPageable(PageRequest.of((currentPage - 1) * 10, pageSize))
                .build();
        SearchHits<ListItemDTO> searchHits = elasticsearchRestTemplate.search(nativeSearchQuery, ListItemDTO.class);
        List<SearchHit<ListItemDTO>> hits = searchHits.getSearchHits();
        List<ListItemDTO> listItemDTOList = new ArrayList<>();
        for (SearchHit<ListItemDTO> hit : hits) {
            Map<String, List<String>> highlightFields = hit.getHighlightFields();
            ListItemDTO content = hit.getContent();
            content.setItemName(highlightFields.get("itemName") == null ? content.getItemName() : highlightFields.get("itemName").get(0));
            content.setAbstractMessage(highlightFields.get("abstractMessage") == null ? content.getAbstractMessage() : highlightFields.get("abstractMessage").get(0));
            content.setImgUrl(dmImageFeign.findItemPosterImageByItemId(content.getId()));
            listItemDTOList.add(content);
        }
        ListDTO listDTO = new ListDTO();
        listDTO.setCurrentPage(currentPage.longValue());
        listDTO.setPageCount(pageSize.longValue());
        listDTO.setTotal(new Long(hits.size()));
        listDTO.setRows(listItemDTOList);
        listDTO.setPageCount(new Long(hits.size() / pageSize) + 1);
        listDTO.setPageSize(5L);
        return VoUtil.returnSuccess(listDTO);
    }

    public CommonResponse guessLike(Long itemTypeId) {
        List<ItemFloorDTO> itemFloorDTOList = itemMapper.findItemByItemType1IdOrItemType2Id(itemTypeId);
        for (ItemFloorDTO itemFloorDTO : itemFloorDTOList) {
            itemFloorDTO.setImgUrl(dmImageFeign.findItemPosterImageByItemId(itemFloorDTO.getId()));
        }
        return VoUtil.returnSuccess(itemFloorDTOList);
    }
}
